import type { RsbuildPlugin } from '@rsbuild/core';
import { SharpOptions } from './types.js';
import path from 'path';
import { fileURLToPath } from 'url';

// ES 模块中的 __dirname 替代方案
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export type { SharpOptions } from './types.js';

/**
 * Rsbuild Sharp 插件
 * 基于 Sharp 的高性能图像优化插件
 */
export const pluginSharp = (options: SharpOptions = {}): RsbuildPlugin => ({
  name: 'rsbuild:sharp',

  setup(api) {
    // 可选：在构建开始/结束时输出提示日志
    if (options.debug) {
      api.onBeforeBuild(() => {
        console.log('🖼️  Sharp image optimization started...');
      });
      api.onAfterBuild(() => {
        console.log('🎉 Sharp optimization completed!');
      });
    }

    // 修改 Rspack 配置以处理图像资源
    api.modifyRspackConfig((config) => {
      // 确保 module.rules 存在
      config.module = config.module || {};
      config.module.rules = config.module.rules || [];

      // 添加图像处理规则
      const imageExtensions = options.filter?.include || ['.jpg', '.jpeg', '.png', '.webp', '.avif', '.tiff'];
      const imageRegex = new RegExp(`\\.(${imageExtensions.map(ext => ext.slice(1)).join('|')})$`, 'i');

      config.module.rules.unshift({
        test: imageRegex,
        enforce: 'pre',
        type: 'asset/resource',
        use: [
          {
            loader: path.resolve(__dirname, 'loader.mjs'),
            options: {
              sharpOptions: options
            }
          }
        ]
      });

      return config;
    });
  }
});

// 默认导出
export default pluginSharp;
